<template>
  <view>
    <scroll-view class="main"
                 scroll-y="true"
                 :scroll-top="scrollTop"
                 @scroll="handleScrollEvt"
                 @touchmove="handleTouchMove"
                 @touchstart="handleTouchStart"
                 @touchend="handleTouchEnd">

      <view v-if="topH > 0" :style="{'border': '1px solid red', 'height': topH + 'px'}"></view>

      <view v-for="(item, index) in 36" :key="index">
        <view style="margin-left: 25px;">
          <text>{{ item }}</text>
        </view>
      </view>

      <view :style="{'border': '1px solid red', 'height': bottomH + 'px'}"></view>

    </scroll-view>
  </view>
</template>
<script>
export default {
  data(){
    return {
      starty: 0,
      endy: 0,
      scrollTop: 0,
      // 通过微信小程序的“正交”API来判断元素是否出现在屏幕视口上
      intersectionRect_height: 0,
      intersectionRect_top: 0,
      //
      flagTouchMoving: false, // 是否正在滑动屏幕
      touchStartTime: 0, // 记录`touchstart`的时间戳
    }
  },
  computed: {
    topH(){
      const y = (this.endy - this.starty)
      return y > 0 ? (y > 72 ? 72 : y) : 0
    },
    bottomH(){
      const y = (this.starty - this.endy)
      return y > 0 ? (y > 72 ? 72 : y) : 0
    },
    // viewH() {
    //   return this.bottomH + 10
    // }
  },
  methods: {
    resetY(){
      this.starty = this.endy = 0
    },
    handleTouchMove(evt){
      console.log('>> handleTouchMove: ')
      this.endy = evt.touches[0].pageY
      // this.scrollTop = this.scrollTop + this.viewH
      // this.flagTouchMoving = true
      if (this.bottomH > 0) {
        this.scrollTop = this.scrollTop + this.bottomH
      }
    },
    handleTouchStart(evt){
      this.endy = this.starty = evt.touches[0].pageY
      this.touchStartTime = (new Date()).getTime()
    },
    handleTouchEnd(evt){
      this.resetY()
      this.flagTouchMoving = false
      const interval = (new Date()).getTime() - this.touchStartTime
      console.log('interval: ', interval) // 可以根据 `interval` 的大小来决定是否进行某些动作
    },
    handleScrollEvt(evt) {
      const that = this

      let scrollTop = evt.detail.scrollTop
      if (that._scrollEvtTimer) {
        clearTimeout(that._scrollEvtTimer)
      }
      that._scrollEvtTimer = setTimeout(()=>{
        // 延迟设置 `scrollTop` , 先把`evt.detail.scrollTop`存储在`scrollTop`变量中
        that.scrollTop = scrollTop
      }, 50)

      // if (!that.flagTouchMoving) { // 手指没有滑动时执行下面的代码，手指在滑动屏幕时不修改`scrollTop`
      // }

    }
  }
}
</script>
<style lang="scss">
.main {
  border: #0ea391 1px solid;
  height: calc(97vh);
}
</style>
